//show menu in terminal
//menu has 3 options: 1. add, 2. query, 3. exit
//select option and execute corresponding function
//if option is not valid, show error message and ask for input again
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import { db } from './db.js';

const rl = readline.createInterface({ input, output });

async function menu() {
    const answer = await rl.question('Select an option:\n1. Add\n2. Query\n3. Exit\n');
    switch (answer) {
        case '1':
            await add();
            break;
        case '2': 
            await query();
            break;
        case '3':
            rl.close();
            break;
        default:
            console.log('Invalid option');
            await menu();
            break;
    }
}

//function add, ask for username, email and password, then call insert function from db.js
const add = async () => {
    const username = await rl.question('Enter username: ');
    const email = await rl.question('Enter email: ');
    const password = await rl.question('Enter password: ');
    await db.insert({username, email, password});
    await menu();
}

//function query, ask for username, then call query function from db.js
const query = async () => {
    const username = await rl.question('Enter username: ');
    const result = await db.query(username);
    console.log(`Found user: ${JSON.stringify(result)}`);
    await menu();
}

menu().catch(console.error);